package com.sto.stoapp.activity.aviation;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.RouteManager;
import com.sto.stoapp.db.manager.SiteFullManager;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.entity.RouteEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

import java.util.ArrayList;
import java.util.List;

@SuppressLint("HandlerLeak")
public class StoAviArrivedBagActivity extends StoListenerActivity {

	private StoHhmEditText route;
	private StoHhmEditText nextStation;
	private StoHhmEditText centerDes;
	// private StoHhmEditText code;
	private DataBusinessEntity dataBusiness;

	private List<EditText> edit = new ArrayList<EditText>();

	private int ROUTE_LENGTH = 8;
	// private String BAGHead = "900";

	private String nextStationCode = "";
	private String nextStationName = "";
	// 路由号
	private String routeCode = "";
	private String centerDesCode = "";
	private String centerDesName = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_avi_arrived_bag);
		this.setTitleBottom(R.string.arrived_bag,
				HomeBroadAction.AVIATION_SCANNER_BROAD);
		dataBusiness = new DataBusinessEntity();
		dataBusiness.initInsertData();
		initPointLayout(true);
		initWidget();
		initListen();
		initScanListener();
		initScanRecordAdapter(EnumTableNames.STATUS_TABLE_AVIATION_SCAN_ARRIVED_BAG);
	}

	/*
	 * 初始化控件
	 */
	private void initWidget() {
		route = (StoHhmEditText) findViewById(R.id.avi_route_number);
		nextStation = (StoHhmEditText) this.findViewById(R.id.avi_next_station);
		centerDes = (StoHhmEditText) findViewById(R.id.avi_destination);
		code = (StoHhmEditText) this.findViewById(R.id.avi_bag_code_text);
		edit.add(nextStation);
		edit.add(centerDes);
		edit.add(code);
		addUploadTable(EnumTableNames.STATUS_TABLE_AVIATION_SCAN_ARRIVED_BAG);
	}

	// 处理扫描数据
	@SuppressLint("NewApi")
	private void processScanData() {
		try {
			/*
			 * 路由号可跳过
			 * 
			 * @date 2014-05-28
			 */
			if (route.getText().toString().length() <= 0) {
				/*
				 * Helper.showSoundToast(this,
				 * getString(R.string.route_is_empty), false);
				 * route.requestFocus(); return;
				 */
			} else {
				if (nextStationCode.length() <= 0
						|| centerDesCode.length() <= 0) {
					Helper.showSoundToast(this,
							getString(R.string.route_is_undefined), false);
					route.setText("");
					route.requestFocus();
					return;
				}
			}
			if (addPieceRecord()) {
				this.addCodeNumber();
				setSaveData(true);
				// SoundManager.getInstance(this).playSuccessSound();
				Helper.showSoundAndVibrator(this, true);
				code.setSelection(code.length());
				addScanRecordInfo(code.getText().toString());
				code.setText("");
			}
			// 提示插入数据失败
			else {
				Helper.showSoundToast(this,
						getString(R.string.bag_code_repeat), false);
			}
			ScanOpen();
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("processScanData", e.getMessage());
		}
	}

	// 增加一条记录
	private boolean addPieceRecord() {
		boolean ret;

		// 扫描类型
		dataBusiness
				.setCommand_type(EnumTableNames.STATUS_TABLE_AVIATION_SCAN_ARRIVED_BAG
						.getOpCode());
		// 设置单号 ，为了在记录查询中显示
		dataBusiness.setBar_code_number(code.getText().toString());
		//单号类型
		dataBusiness.setCodeType(getExpType(code.getText().toString()));
		// 包号
		dataBusiness.setBag_number(code.getText().toString());
		// 下一站
		dataBusiness.setNext_station(nextStationCode);
		// 目的地
		dataBusiness.setUser_defined3(centerDesCode);
		// 路由
		if (routeCode.length() <= 0) {
			dataBusiness.setReason_number("");
		} else {
			dataBusiness.setReason_number(routeCode);
		}
		// 网点编号
		dataBusiness.setNet_code(StoFilePreference.getInstance(this)
				.getSiteCode());
		// 工号
		dataBusiness.setJob_number(StoFilePreference.getInstance(this)
				.getUserCode());
		// 插入数据
		ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
				EnumTableNames.STATUS_TABLE_AVIATION_SCAN_ARRIVED_BAG);
		return ret;
	}

	private void selectRoute() {
		try {
			routeCode = route.getText().toString();
			QueryRouteThread thread = new QueryRouteThread();
			thread.start();
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("selectRoute", e.getMessage());
		}
	}

	/*
	 * 监听控件
	 */
	@SuppressLint("NewApi")
	private void initListen() {
		route.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				onBackPressed();
			}

			@Override
			public void onEditClickListener(View v) {
				selectRoute(); // 搜索路由数据
			}
		});
		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				route.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
				if (code.getText().toString().length() == 0) {
					Helper.showSoundToast(StoAviArrivedBagActivity.this,
							getString(R.string.code_empty), false);
				} else {
					if (CheckScanCode(code.getText().toString())) {
						onScanResults(code.getText().toString());
					} else {
						code.setText("");
					}
				}
			}
		});

	}

	@Override
	public void onBackPressed() {
		showNotice();
	}

	private boolean CheckScanCode(String code) {
		boolean ret = false;
		EnumScanCode status = ProcessScanCode.getInstance(this)
				.ScanCodeResolve(code,
						EnumTableNames.STATUS_TABLE_AVIATION_SCAN_ARRIVED_BAG);
		switch (status) {
		// 条码空
		case CODE_EMPTY:
			break;

		// 非法条码
		case CODE_ILLEGAL:
			Helper.showSoundToast(this, getString(R.string.error_code), false);
			break;
		// 成功条码
		case CODE_WAY_BILL:
			ret = true;
			break;
		default:
			break;
		}

		return ret;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		edit.clear();
		super.onDestroy();
	}

	class QueryRouteThread extends Thread {

		@Override
		public void run() {
			super.run();
			final RouteEntity entity = RouteManager.getInstance(
					StoAviArrivedBagActivity.this).queryByRouteCode(routeCode);
			if (entity != null) {
				nextStationCode = entity.getNextStation();
				centerDesCode = entity.getCenterDes();
				if (entity.getNextStation().length() > 0) {
					nextStationName = SiteFullManager.getInstance(
							StoAviArrivedBagActivity.this).querySiteCodeName(
							nextStationCode);
				}
				if (entity.getCenterDes().length() > 0) {
					centerDesName = SiteFullManager.getInstance(
							StoAviArrivedBagActivity.this).querySiteCodeName(
							centerDesCode);
				}
			}
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (entity != null) {
						nextStation
								.setText((nextStationName.length() > 0) ? nextStationName
										: nextStationCode);
						centerDes
								.setText((centerDesName.length() > 0) ? centerDesName
										: centerDesCode);
						code.requestFocus();
					} else {
						route.setText("");
						routeCode = "";
						nextStationCode = "";
						nextStationName = "";
						nextStation.setText("");
						centerDesCode = "";
						centerDesName = "";
						centerDes.setText("");
						Helper.showSoundToast(StoAviArrivedBagActivity.this,
								"未定义，请到业务设置中更新数据", false);
					}
				}
			});
		}
	}

	@Override
	protected void handlerScanData(String scanData) {

		if (scanData != null && !scanData.equals("")) {
			String result = scanData;

			// 如果扫描的单号是路由
			if (result.length() == ROUTE_LENGTH) {
				route.setText(result);
				SoundManager.getInstance(StoAviArrivedBagActivity.this)
						.playSuccessSound();
				selectRoute();
			} else {
				code.setText(result);
				code.setSelection(code.length());

				if (CheckScanCode(result)) {
					processScanData();
				}
				code.setText("");
			}
		} else {
		}

	}
}
